import { ipcMain, dialog } from 'electron'
import fs from 'fs'
import path from 'path'

interface RenameImagesParams {
  folderPath: string
  startNumber: number
}

interface RenameImagesResult {
  success: boolean
  message: string
  count?: number
}

const SUPPORTED_IMAGE_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']

export function setupFileOperationsHandlers(): void {
  // 处理文件对话框
  ipcMain.handle('show-open-dialog', async (_, options) => {
    return dialog.showOpenDialog(options)
  })

  // 处理图片重命名
  ipcMain.handle('rename-images', (_, params: RenameImagesParams): RenameImagesResult => {
    try {
      // 检查文件夹是否存在
      fs.accessSync(params.folderPath)

      // 读取文件夹内容
      const files = fs.readdirSync(params.folderPath)

      // 过滤图片文件
      const imageFiles = files.filter((file) => {
        const ext = path.extname(file).toLowerCase()
        return SUPPORTED_IMAGE_EXTENSIONS.includes(ext)
      })

      if (imageFiles.length === 0) {
        return {
          success: false,
          message: '所选文件夹中没有图片文件'
        }
      }

      // 按文件名排序，确保重命名顺序一致
      imageFiles.sort()

      let currentNumber = params.startNumber
      let successCount = 0

      // 同步处理所有文件
      imageFiles.forEach((file) => {
        try {
          const ext = path.extname(file)
          const newName = `${currentNumber}${ext}`
          const oldPath = path.join(params.folderPath, file)
          const newPath = path.join(params.folderPath, newName)

          fs.renameSync(oldPath, newPath)
          successCount++
          currentNumber++
        } catch (error) {
          console.error(`重命名文件 ${file} 时出错:`, error)
        }
      })

      return {
        success: true,
        message: `成功重命名 ${successCount} 个文件`,
        count: successCount
      }
    } catch (error) {
      console.error('重命名操作出错:', error)
      return {
        success: false,
        message: error instanceof Error ? error.message : '重命名过程中出错'
      }
    }
  })
}
